module.exports = Behavior({
  properties: {
    attrMap: {
      type: String
    }
  },
  methods: {
    setDataSmart: function (data) {
      // 如未设置双向绑定map，则默认为设置内部属性，走快捷方式
      if ( !this.data.attrMap ) {
        console.log('不存在双向数据流...');
        this.setData( data );
        return;
      }
      
      let {
        parentData,
        innerData
      } = this.splitDataByAttrMap(data, this.data.attrMap);

      // 组件内部数据更新
      if ( Object.keys( innerData ).length ) {
        this.setData( innerData );
      }
      // 来自父组件数据更新，发消息通知父组件
      if ( Object.keys( parentData ).length ) {
        console.log('子组件：双向数据流更新请求...');
        this.triggerEvent( 'onUpdateAttr', parentData );
      }
    },
    /*
    暂时不支持链式属性如：arr[1].name
    */
    splitDataByAttrMap(data, attrMap) {
      
      let parentData = {};
      let innerData = {};
      let attrMaps = attrMap.split( '&' );

      for (let i = 0, len = attrMaps.length; i < len; i ++) {
          let attrs = attrMaps[ i ].split( '=' );
          let childAttr = attrs[ 0 ];
          // attrMap采用省略方式时,表示父子属性名相同
          // 可直接使用childAttr, 如attrMap="popviewShow"
          let parentAttr = attrs[ 1 ] || childAttr;
          parentData[ parentAttr ] = data[ childAttr ];
          data[childAttr] = null;    
      }
      for ( let key in data ) {
          if ( data[ key ] ) {
              innerData[ key ] = data[ key ];
          }
      }
      return {
          parentData,
          innerData
      }
    }
  }
})